#!/bin/bash

# 安装服务
install_service() {
    # 自动获取 recorder.py 的路径
    RECORDER_PATH=$(dirname "$(readlink -f "$0")")/recorder.py

    # 获取当前用户名，支持 sudo 环境
    if [ -n "$SUDO_USER" ]; then
        USER_NAME=$SUDO_USER
    else
        USER_NAME=$(whoami)
    fi

    # 生成 recorder.service 文件
    {
        echo "[Unit]"
        echo "Description=Recorder Service"
        echo "After=network.target"
        echo
        echo "[Service]"
        echo "User=$USER_NAME"
        echo "WorkingDirectory=$(dirname "$RECORDER_PATH")"
        echo "ExecStart=/usr/bin/python3 "$RECORDER_PATH""
        echo "Restart=always"
        echo "RestartSec=5"
        echo "StandardOutput=append:$(dirname "$RECORDER_PATH")/logs/recorder.log"
        echo
        echo "[Install]"
        echo "WantedBy=multi-user.target"
    } > /etc/systemd/system/recorder.service

    mkdir -p "$(dirname "$RECORDER_PATH")/logs/"

    # 重新加载 systemd 配置
    systemctl daemon-reload

    echo "Recorder 服务已安装。"

    # 启用并启动服务
    echo "开机自启: systemctl enable recorder"
    echo "启动服务: systemctl start recorder"
}

# 卸载服务
uninstall_service() {
    echo "正在停止并卸载 Recorder 服务..."

    # 停止服务
    systemctl stop recorder

    # 禁用服务
    systemctl disable recorder

    # 删除服务文件
    rm -f /etc/systemd/system/recorder.service

    # 重新加载 systemd 配置
    systemctl daemon-reload

    echo "Recorder 服务已卸载。"
}


[ -n "$SUDO_USER" ] && shift 
# 根据传入参数执行相应操作
case "$1" in
    uninstall)
        uninstall_service
        ;;
    *)
        install_service
        ;;
esac